package iNotes.assist;

import com.mysql.cj.Session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.*;

public class Utils {
    public static void close(Connection connection, ResultSet resultSet, Statement... st){
        for(Statement statement:st){
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static boolean checkBelonging(Connection connection,int uid,int noteID) throws SQLException {
        int cnt = 0;
        CallableStatement c = connection.prepareCall("{call checkBelonging(?,?,?)}");
        c.setInt(1,uid);
        c.setInt(2,noteID);
        c.registerOutParameter(3,Types.INTEGER);
        c.execute();
        cnt = c.getInt(3);
        c.close();
        return cnt != 0;
    }
    public static boolean checkToken(HttpSession session, HttpServletRequest request){
        String requestToken = (String) request.getParameter("_token");
        String sessionToken = (String) session.getAttribute("_token");
        if(requestToken == null || sessionToken == null) return false;
        return requestToken.equals(sessionToken);
    }
}
